package com.zkyc.framework.website.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zkyc.framework.common.constant.NumberConstant;
import com.zkyc.framework.common.exception.ResultCode;
import com.zkyc.framework.common.mapper.ApproveProcessMapper;
import com.zkyc.framework.common.mapper.CenterMapper;
import com.zkyc.framework.common.mapper.UserMapper;
import com.zkyc.framework.common.pojo.ApproveProcess;
import com.zkyc.framework.common.pojo.Center;
import com.zkyc.framework.common.pojo.User;
import com.zkyc.framework.common.vo.ResultVO;
import com.zkyc.framework.common.vo.website.ApproveProcessPageVO;
import com.zkyc.framework.website.client.UserClient;
import com.zkyc.framework.website.service.ApproveProcessService;
import com.zkyc.framework.website.util.TokenUserUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (ApproveProcess)表服务实现类
 *
 * @author libingchuan
 * @since 2023-02-15 16:21:27
 */
@Service("approveProcessService")
public class ApproveProcessServiceImpl implements ApproveProcessService {
    @Resource
    private ApproveProcessMapper approveProcessMapper;

    @Resource
    private CenterMapper centerMapper;

    @Resource
    private TokenUserUtil tokenUserUtil;

    @Resource
    private UserMapper userMapper;

    @Autowired
    private UserClient userClient;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ApproveProcess queryById(Integer id) {
        return this.approveProcessMapper.selectById(id);
    }

    /**
     * 分页查询
     *
     * @return 查询结果
     */
    @Override
    public ResultVO queryByPage(ApproveProcessPageVO approveProcessPageVo) {
        if (approveProcessPageVo == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        approveProcessPageVo.checkParam();
        Integer code;
        Integer centerId = null;
        String currentUserId = TokenUserUtil.getCurrentUserId();
        if (currentUserId.equals("superadmin")) {
            code = NumberConstant.NUMBER_0;
        } else {
            code = userMapper.judgeIsAdmin(currentUserId);
        }
        if (code == null) {
            User user = userMapper.selectById(currentUserId);
            centerId = user.getCenterId();
        }
        Page page = new Page(approveProcessPageVo.getPage(), approveProcessPageVo.getSize());
        LambdaQueryWrapper<ApproveProcess> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (approveProcessPageVo.getType() != null) {
            lambdaQueryWrapper.eq(ApproveProcess::getType, approveProcessPageVo.getType());
        }
        if (approveProcessPageVo.getCenterId() != null) {
            lambdaQueryWrapper.eq(ApproveProcess::getCenterId, approveProcessPageVo.getCenterId());
        }
        if (StringUtils.isNotBlank(approveProcessPageVo.getApprover())) {
            lambdaQueryWrapper.and(x -> x.like(ApproveProcess::getApprover1, approveProcessPageVo.getApprover()).or()
                    .like(ApproveProcess::getApprover2, approveProcessPageVo.getApprover()));
        }
        if (centerId != null && centerId != 0) {
            lambdaQueryWrapper.eq(ApproveProcess::getCenterId, centerId);
        }
        IPage<ApproveProcess> page1 = approveProcessMapper.selectPage(page, lambdaQueryWrapper);
        page1.getRecords().forEach(approveProcess -> {
            approveProcess.setCenterName(centerMapper.selectById(approveProcess.getCenterId()).getCenterName());
        });
        return ResultVO.data(page1);
    }

    /**
     * 查询
     *
     * @return 查询结果
     */
    @Override
    public ResultVO queryList() {
        return ResultVO.data(approveProcessMapper.selectList(null));
    }


    /**
     * 新增数据
     *
     * @param approveProcess 实例对象
     * @return 实例对象
     */
    @Override
    public ResultVO insert(ApproveProcess approveProcess) {
        if (approveProcess == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        approveProcessMapper.insert(approveProcess);
        return ResultVO.success(ResultCode.SUCCESS);
    }

    /**
     * 修改数据
     *
     * @param approveProcess 实例对象
     * @return 实例对象
     */
    @Override
    public ResultVO update(ApproveProcess approveProcess) {
        if (approveProcess == null && approveProcess.getId() == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        if (StringUtils.isNotBlank(approveProcess.getApprover1())) {
            User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, approveProcess.getApprover1()));
            if (user == null) {
                return ResultVO.fail(ResultCode.PARAM_INVALID);
            } else {
                Integer code = userMapper.judgeRightExist(user.getId());
                if (code == null) {
                    return ResultVO.fail(ResultCode.NO_APPROVE_RIGHT);
                }
            }
        }
        if (StringUtils.isNotBlank(approveProcess.getApprover2())) {
            User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, approveProcess.getApprover2()));
            if (user == null) {
                return ResultVO.fail(ResultCode.PARAM_INVALID);
            } else {
                Integer code = userMapper.judgeRightExist(user.getId());
                if (code == null) {
                    return ResultVO.fail(ResultCode.NO_APPROVE_RIGHT);
                }
            }
        }
        if (StringUtils.isNotBlank(approveProcess.getApprover2()) && approveProcess.getApprover2().equals(approveProcess.getApprover1())) {
            ApproveProcess approveProcess1 = approveProcessMapper.selectById(approveProcess.getId());
            if (approveProcess1.getApprover1().equals(approveProcess.getApprover2())) {
                return ResultVO.fail(ResultCode.APPROVE1_EXIST);
            } else {
                return ResultVO.fail(ResultCode.APPROVE2_EXIST);
            }
        }
        approveProcessMapper.updateById(approveProcess);
        return ResultVO.success(ResultCode.SUCCESS);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public ResultVO deleteById(Integer id) {
        if (id == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        if (queryById(id) == null) {
            return ResultVO.fail(ResultCode.SERVE_ERROR);
        }
        approveProcessMapper.deleteById(id);
        return ResultVO.success(ResultCode.SUCCESS);
    }

    @Override
    public ResultVO init() {
        List<ApproveProcess> approveProcesses = approveProcessMapper.selectList(null);
        if (approveProcesses.size() == 0) {
            List<Center> centers = centerMapper.selectList(null);
            User user = tokenUserUtil.getCurrentUser();
            String username = user.getUsername();
            centers.forEach(center -> {
                ApproveProcess approveProcess = new ApproveProcess();
                approveProcess.setCenterId(center.getId());
                approveProcess.setType(1);
                approveProcess.setCreatedBy(username);
                approveProcessMapper.insert(approveProcess);
                approveProcess.setType(2);
                approveProcessMapper.insert(approveProcess);
            });
        }
        return ResultVO.success(ResultCode.SUCCESS);
    }

    @Override
    public ResultVO judgeIdentity() {
        HashMap<String, String> hashMap = new HashMap<>();
        String currentUserId = TokenUserUtil.getCurrentUserId();
        if (currentUserId != null) {
            ResultVO<?> userById = userClient.getUserById(currentUserId);
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(userById));
            User user = JSONObject.parseObject(jsonObject.getString("data"), User.class);

            Integer code = userMapper.judgeIsAdmin(currentUserId);
            if (currentUserId.equals("superadmin") || code != null) {
                hashMap.put("1", "0");
                hashMap.put("2", "0");
                return ResultVO.data(hashMap);
            } else {
                List<ApproveProcess> approveProcesses = approveProcessMapper.selectList(new LambdaQueryWrapper<ApproveProcess>()
                        .eq(ApproveProcess::getApprover1, user.getUsername()));
                for (ApproveProcess approveProcess : approveProcesses) {
                    hashMap.put(approveProcess.getType().toString(), "1");
                }
                List<ApproveProcess> approveProcesses2 = approveProcessMapper.selectList(new LambdaQueryWrapper<ApproveProcess>()
                        .eq(ApproveProcess::getApprover2, user.getUsername()));
                for (ApproveProcess approveProcess : approveProcesses2) {
                    hashMap.put(approveProcess.getType().toString(), "2");
                }
            }
        }
        return ResultVO.data(hashMap);
    }

    @Override
    public ResultVO isTransmit(Integer type) {
        String currentUserId = TokenUserUtil.getCurrentUserId();
        if (currentUserId != null) {
            ResultVO<?> userById = userClient.getUserById(currentUserId);
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(userById));
            User user = JSONObject.parseObject(jsonObject.getString("data"), User.class);
            if (user != null) {
                ApproveProcess approveProcesses = approveProcessMapper.selectOne(new LambdaQueryWrapper<ApproveProcess>()
                        .eq(ApproveProcess::getApprover1, user.getUsername()).eq(ApproveProcess::getType, type));
                if (approveProcesses != null && StringUtils.isNotBlank(approveProcesses.getApprover2())) {
                    return ResultVO.data(true);
                }
            }
        }
        return ResultVO.data(false);
    }

    public boolean judgeNotOrganizationAndIsAdmin(String userId) {
        boolean flag = false;
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, userId));
        if (user != null) {
            if (user.getOrganizationId() != null) {
                return flag;
            }
        }else {
            return  flag;
        }
        Integer exist = userMapper.judgeIsAdmin(userId);
        if (exist != null) {
            flag = true;
        }
        return flag;
    }
}
